﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using RestSharp;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using DingTalk.Common;

namespace ScanPhyto.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UploadController : ControllerBase
    {

        private readonly ILogger<UploadController> _logger;

        public UploadController(ILogger<UploadController> logger)
        {
            _logger = logger;
        }
        const string API_KEY = "eKpYBSFugGB1EGgbGHs7zSik";
        const string SECRET_KEY = "pinyfzTv2Kd44FNq9ahOcwIlbxLchO3O";


        //[HttpPost]
        //public dynamic TakeImage([FromForm] string file)
        //{
        //    var client = new RestClient($"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate?access_token={GetAccessToken()}");
        //    client.Timeout = -1;
        //    var request = new RestRequest(Method.POST);
        //    request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
        //    request.AddHeader("Accept", "application/json");
        //    // image 可以通过 GetFileBase64Content('C:\fakepath\微信图片_20221203144337.jpg') 方法获取
        //    //request.AddParameter("image", "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8Q...");
        //    request.AddParameter("image", file);
        //    IRestResponse response = client.Execute(request);
        //    //Console.WriteLine(response.Content);
        //    return response.Content;

        //}
        /// <summary>
        /// 接收Base64编码格式的图片
        /// </summary>
        //public void Upload()
        //{
        //    //获取base64编码的图片
        //    HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];
        //    string text = context.Request.Form["file"];

        //    //获取文件储存路径
        //    string path = context.Request.MapPath("~/"); //获取当前项目所在目录
        //    string datetime = GetTimeStamp();
        //    string suffix = ".jpg"; //文件的后缀名根据实际情况
        //    string strPath = path + "App_Data/" + datetime + suffix;

        //    //获取图片并保存
        //    Base64ToImg(text.Split(',')[1]).Save(strPath);
        //}

        ////解析base64编码获取图片
        //private Bitmap Base64ToImg(string base64Code)
        //{
        //    MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64Code));
        //    return new Bitmap(stream);
        //}

        ////获取当前时间段额时间戳
        //public string GetTimeStamp()
        //{
        //    TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        //    return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        //}

        [HttpPost]
        public async Task<ActResult> UploadFiles(List<IFormFile> files)
        {
            ActResult act = new ActResult();
            long size = files.Sum(f => f.Length);       //统计所有文件的大小 
            var filepath = Directory.GetCurrentDirectory() + "\\file";  //存储文件的路径 
            if (!Directory.Exists(filepath))
            {
                Directory.CreateDirectory(filepath);
            }

            foreach (var item in files)     //上传选定的文件列表
            {
                if (item.Length > 0)        //文件大小 0 才上传
                {
                    var thispath = filepath + "\\" + item.FileName;     //当前上传文件应存放的位置

                    if (System.IO.File.Exists(thispath) == true)        //如果文件已经存在,跳过此文件的上传
                    {
                        _logger.LogError("文件已存在：" + thispath.ToString());
                        System.IO.File.Delete(thispath);
                        continue;
                    }
                    //上传文件
                    using (var stream = new FileStream(thispath, FileMode.Create))      //创建特定名称的文件流
                    {
                        try
                        {
                            item.CopyToAsync(stream);     //上传文件
                            //清空缓冲区数据
                            stream.Flush();
                        }
                        catch (Exception ex)        //上传异常处理
                        {
                            _logger.LogError("ex：" + ex.ToString());
                        }
                        act.data = TakeImgs(thispath);
                    }

                    act.code = 0;
                    act.msg = "操作成功!";
                }
            }
            return act;
        }

        [HttpPost]
        public dynamic TakeImgs([FromForm] string path)
        {
            var client = new RestClient($"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate?access_token={GetAccessToken()}");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddHeader("Accept", "application/json");
            // image 可以通过 GetFileBase64Content('C:\fakepath\微信图片_20221203144337.jpg') 方法获取
            //request.AddParameter("image", "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8Q...");

            request.AddParameter("image", GetFileContentAsBase64(path));
            IRestResponse response = client.Execute(request);
            _logger.LogInformation(response.Content);
            //Console.WriteLine(response.Content);
            return response.Content;
        }

        /**
        * 获取文件base64编码
        * @param path 文件路径
        * @return base64编码信息，不带文件头
        **/
        private string GetFileContentAsBase64(string path)
        {
            using (FileStream filestream = new FileStream(path, FileMode.Open))
            {
                byte[] arr = new byte[filestream.Length];
                filestream.Read(arr, 0, (int)filestream.Length);
                string base64 = Convert.ToBase64String(arr);
                return base64;
            }
        }

        private string GetFileContentAsBase64(FileStream filestream)
        {
            byte[] arr = new byte[filestream.Length];
            filestream.Read(arr, 0, (int)filestream.Length);
            string base64 = Convert.ToBase64String(arr);
            return base64;
        }


        /**
        * 使用 AK，SK 生成鉴权签名（Access Token）
        * @return 鉴权签名信息（Access Token）
        */
        private static string GetAccessToken()
        {
            var client = new RestClient($"https://aip.baidubce.com/oauth/2.0/token");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddParameter("grant_type", "client_credentials");
            request.AddParameter("client_id", API_KEY);
            request.AddParameter("client_secret", SECRET_KEY);
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);
            var result = JsonConvert.DeserializeObject<dynamic>(response.Content);
            return result.access_token.ToString();
        }
    }
}
